﻿using Consul;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Zd.MicroService.WebApi.Comment
{
    public static class ConsultHelper
    {
        /// <summary>
        /// 将当前站点注入到Consul
        /// </summary>
        /// <param name="configuration"></param>
        public static void ConsulRegister(this IConfiguration configuration) {
            //初始化Consul服务
            ConsulClient client = new ConsulClient(c => {
                c.Address = new Uri("http://localhost:8500");
                c.Datacenter = "dc1";
            });

            //站点做集群时ip和端口都会不一样，所以我们通过环境变量来确定当前站点的ip与端口
            string ip = configuration["ip"];
            int port = int.Parse(configuration["port"]);
            client.Agent.ServiceRegister(new AgentServiceRegistration { 
                ID = "service"+Guid.NewGuid(), //注册进Consul后给个唯一id,
                Name = "ZdConsulService", //站点做集群时，Name作为该集群的群名，
                Address = ip,
                Port = port,
                Tags = null, //这个就是一个随意的参数，文章后面做负载均衡的时候说
                Check = new AgentServiceCheck { 
                    Interval = TimeSpan.FromSeconds(10),
                    HTTP = $"http://{ip}:{port}/api/health",
                    Timeout = TimeSpan.FromSeconds(5),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5)
                }
            });
        }
    }
}
